package com.ijianji.lib_onekeylogin

import android.app.Application
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.TokenRet
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate

/**
 * 一键登录相关工具类,context最好传递application
 */
class OneKeyLoginUtils(private val context: Application) {

    /**
     * 一键登录认证工具
     */
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null

    /**
     * 一键登录认证回调
     */
    private var mTokenResultListener: TokenResultListener? = null

    @JvmField
    var loadingListener: LoadingListener? = null

    @JvmField
    var authTokenListener: AuthTokenListener? = null

    init {
        val authKey = context.getString(R.string.one_key_login_auth_key)
        initOneKeyLogin(authKey)
    }

    /**
     * 初始化阿里云一键登录相关
     *
     * @param accessToken 阿里云后台配置应用后得到的accessToken
     */
    private fun initOneKeyLogin(accessToken: String) {
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                hideLoading()
                val tokenRet = TokenRet.fromJson(s)
                if (ResultCode.CODE_ERROR_ENV_CHECK_SUCCESS == tokenRet.code) {
                    getOneKeyLoginToken()
                } else if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                    //登录成功
                    mPhoneNumberAuthHelper?.hideLoginLoading()
                    mPhoneNumberAuthHelper?.quitLoginPage()
                    authTokenListener?.authTokenSuccess(tokenRet.token)
                } else if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                    //授权页启动成功
                } else {
                    showToast(tokenRet.msg)
                }
            }

            override fun onTokenFailed(s: String) {
                hideLoading()
                val tokenRet = TokenRet.fromJson(s)
                if (ResultCode.CODE_ERROR_NO_MOBILE_NETWORK_FAIL == tokenRet.code) {
                    showToast("一键登录当前不可用，未开启移动网络或其他问题")
                } else {
                    showToast(tokenRet.msg)
                }
                if (ResultCode.CODE_ERROR_NO_MOBILE_NETWORK_FAIL == tokenRet.code || ResultCode.CODE_ERROR_NO_MOBILE_NETWORK_FAIL == tokenRet.code) {
                    mPhoneNumberAuthHelper?.quitLoginPage()
                }
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(context, mTokenResultListener)
        mPhoneNumberAuthHelper?.removeAuthRegisterXmlConfig()
        mPhoneNumberAuthHelper?.removeAuthRegisterViewConfig()
        mPhoneNumberAuthHelper?.setAuthSDKInfo(accessToken)
        val dialogWidth = 310
        val dialogHeight = 380
        val logBtnHeight = 50
        mPhoneNumberAuthHelper?.addAuthRegisterXmlConfig(AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.one_key_login_dialog_top_title_layout, object : AbstractPnsViewDelegate() {
                    override fun onViewCreated(view: View) {
                        findViewById(R.id.ivQuitLogin).setOnClickListener { mPhoneNumberAuthHelper?.quitLoginPage() }
                        findViewById(R.id.tvOtherLogin).setOnClickListener {
                            mPhoneNumberAuthHelper?.quitLoginPage()
                            authTokenListener?.clickOtherLogin()
                        }
                    }
                })
                .build())
        mPhoneNumberAuthHelper?.setAuthUIConfig(AuthUIConfig.Builder()
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#279DFF"))
                .setPrivacyState(false)
                .setCheckboxHidden(true)
                .setNavHidden(true)
                .setSloganHidden(false)
                .setSloganOffsetY(27)
                .setSwitchAccHidden(true)
                .setNavReturnHidden(true)
                .setLogBtnOffsetY(127)
                .setDialogBottom(false)
                .setLightColor(false)
                .setStatusBarColor(Color.BLACK)
                .setNavColor(Color.BLACK)
                .setWebNavColor(Color.BLACK)
                .setWebViewStatusBarColor(Color.BLACK)
                .setWebNavTextColor(Color.WHITE)
                .setLogoOffsetY(0)
                .setLogoWidth(42)
                .setLogoHeight(42)
                .setLogoImgPath("mytel_app_launcher")
                .setNumFieldOffsetY(69)
                .setNumberSize(22)
                .setLogBtnWidth(dialogWidth - 26)
                .setLogBtnMarginLeftAndRight(15)
                .setLogBtnHeight(logBtnHeight)
                .setLogBtnTextSize(16)
                .setLogBtnOffsetY(127)
                .setLogBtnText("本机号一键登录")
                .setLogBtnBackgroundPath("one_key_login_bg")
                .setPageBackgroundPath("dialog_page_background")
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setPrivacyBefore("登录即表明已阅读同意\n")
                .setProtocolLayoutGravity(Gravity.CENTER_HORIZONTAL)
                .setDialogWidth(dialogWidth)
                .setDialogHeight(dialogHeight)
                .setScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)
                .create())
    }

    fun destroyOneKeyLogin() {
        if (mPhoneNumberAuthHelper != null) {
            mTokenResultListener = null
            mPhoneNumberAuthHelper?.removeAuthRegisterViewConfig()
            mPhoneNumberAuthHelper?.removeAuthRegisterXmlConfig()
            mPhoneNumberAuthHelper?.setAuthListener(null)
            mPhoneNumberAuthHelper?.addAuthRegisterXmlConfig(null)
            mPhoneNumberAuthHelper = null
        }
    }

    /**
     * 检查一键登录环境是否可以用
     */
    fun checkOneKeyLoginEnv() {
        val authKey = context.getString(R.string.one_key_login_auth_key)
        if (authKey.isEmpty()) {
            showToast("你还没有配置必要参数，请配置后重新打包运行!")
            return
        }
        showLoading("登录环境检测中...")
        if (mPhoneNumberAuthHelper != null) {
            mPhoneNumberAuthHelper?.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN)
        }
    }


    private fun getOneKeyLoginToken() {
        if (mPhoneNumberAuthHelper != null) {
            showLoading("请等待")
            mPhoneNumberAuthHelper?.getLoginToken(context, 4000)
        }
    }


    private fun showToast(content: String) {
        Toast.makeText(context, content, Toast.LENGTH_SHORT).show()
    }

    private fun hideLoading() {
        loadingListener?.hideLoadingView()
    }


    private fun showLoading(content: String) {
        loadingListener?.showLoadingView(content)
    }


    /**
     * loading对话框的回调
     */
    interface LoadingListener {

        fun hideLoadingView()

        fun showLoadingView(content: String)
    }


    interface AuthTokenListener {

        /**
         * token获取成功
         */
        fun authTokenSuccess(accessToken: String)

        /**
         * 点击了其他登录方式
         */
        fun clickOtherLogin();
    }

}